package com.keson.door2.util;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.arcsoft.face.FaceFeature;
import com.keson.door2.bean.Face;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MqttClientUtil {
	private static MqttClient sampleClient;
	private static int i = 1;
	private static int magnitudeCache = 0;
	private static int messageId = 0;
	private static int level = 0;

	public static MqttClient getInstance() {
		if(sampleClient==null) {
			try {
				sampleClient = new MqttClient(Constant.broker, Constant.clientNo, new MemoryPersistence());
				final MqttConnectOptions connOpts = new MqttConnectOptions();
				connOpts.setUserName("admin");
				connOpts.setPassword("keson-123".toCharArray());
				connOpts.setCleanSession(true);
				//connOpts.setAutomaticReconnect(true);
				connOpts.setWill(Constant.onlineTopic, Constant.offlineMsg.getBytes(), Constant.onlineQos, false);
				Log.i("MQTT", "正在连接"+Constant.broker);
				sampleClient.setCallback(new MqttCallback() {

					@Override
					public void messageArrived(String topic, MqttMessage message) throws Exception {
						// TODO Auto-generated method stub
						// TODO Auto-generated method stub
						Log.i("接收消息", "接收消息主题 : " + topic);
						Log.i("接收消息", "接收消息Qos : " + message.getQos());
						Log.i("接收消息", "接收消息内容 : " + new String(message.getPayload(),"UTF-8"));
						String msg = new String(message.getPayload(),"UTF-8");
						Log.i("接收消息", "解密消息内容 : " + msg);
						JSONObject info = null;
						try {
							info  = JSONObject.parseObject(msg);
						} catch (Exception e) {
							e.printStackTrace();
						}
//						操作
						if(topic.equals(Constant.actionTopic)) {
							String todo = info.getString("todo");
							if(todo.equals("status")) {
								MqttClientUtil.publishTopic(Constant.onlineTopic, Constant.onlineQos, Constant.onlineMsg,false);
								return;
							}
							JSONArray clients = info.getJSONArray("clients");
							if(clients.contains(Constant.clientNo)) {
								switch (todo) {
									case "update":
										Log.i("软件更新","-开始");
//										try{
//											DownLoadUtil.downLoadFromUrl(Constant.updateUrl+"/"+Constant.appName+".apk", "eqplayer.apk", Environment.getExternalStorageDirectory().toString()+"/Download");
//										}catch (Exception e){
//											e.printStackTrace();
//										}
//
//										Log.i("软件更新","-完毕");
//										Log.i("软件更新","-开始安装");
//										smdt.smdtSilentInstall(Environment.getExternalStorageDirectory().toString()+"/Download/eqplayer.apk",Constant.context);
//										Log.i("软件更新","-安装完毕");
//										reStartApp();
//										Constant.context.startActivity(new Intent(Constant.context, UpdateActivity.class));
										break;
									case "lock":
//										JSONObject config = Constant.getConfigJsonObject();
//										config.put("lock", "1");
//										Constant.updateConfigToFile(config, Constant.getInfoJsonObject());
//									重启软件
//										AppService.reStartApp();
										break;

									case "unLock":
//										JSONObject config1 = Constant.getConfigJsonObject();
//										config1.put("lock", "0");
//										Constant.updateConfigToFile(config1, Constant.getInfoJsonObject());
////									重启软件
//										AppService.reStartApp();
										break;

									case "cloud":
//										JSONObject config2 = Constant.getConfigJsonObject();
//										config2.put("cloud", "1");
//										Constant.updateConfigToFile(config2, Constant.getInfoJsonObject());
////									重启软件
//										AppService.reStartApp();
										break;
									case "unCloud":
//										JSONObject config3 = Constant.getConfigJsonObject();
//										config3.put("cloud", "0");
//										Constant.updateConfigToFile(config3, Constant.getInfoJsonObject());
////									重启软件
//										AppService.reStartApp();
										break;
									case "reboot":
//									重启系统
//										smdt.smdtReboot("reboot");
										break;
									case "shutdown":
//									关闭系统
//										smdt.shutDown();
										break;
									case "readConfig":
//										JSONObject obj = new JSONObject();
//										obj.put("config", Constant.getConfigJsonObject().toJSONString());
//										obj.put("info", Constant.getInfoJsonObject().toJSONString());
//										obj.put("todo", "writeConfig");
//										MqttClientUtil.publishTopic(Constant.actionTopic, Constant.actionQos, obj.toJSONString(),false);
										break;
									case "readLogList":
//										try {
//											JSONObject obj1 = new JSONObject();
//											String logList = "";
//
//											File[] files = new File(Environment.getExternalStorageDirectory().toString()+"/log/dailyLog").listFiles();
//											List<File> fileList = Arrays.asList(files);
//											Collections.sort(fileList, new Comparator<File>() {
//												@Override
//												public int compare(File o1, File o2) {
//													if (o1.isDirectory() && o2.isFile())
//														return -1;
//													if (o1.isFile() && o2.isDirectory())
//														return 1;
//													return o2.getName().compareTo(o1.getName());
//												}
//											});
//
//											for (File file : files) {
//												if (file.isFile()){
//													logList = logList + (logList.equals("")?"":",") + file.getName();
//												}
//											}
//
//											obj1.put("logList", logList);
//											obj1.put("clientNo", Constant.clientNo);
//											obj1.put("todo", "writeLogList");
//											MqttClientUtil.publishTopic(Constant.actionTopic, Constant.actionQos, obj1.toJSONString(),false);
//										} catch (Exception e) {
//											e.printStackTrace();
//										}

										break;
									case "readLogContent":
//										try {
//											JSONObject obj2 = new JSONObject();
//											InputStreamReader fileis = new InputStreamReader(new FileInputStream(Environment.getExternalStorageDirectory().toString()+"/log/dailyLog/"+info.getString("fileName")), "UTF-8");
//											BufferedReader filebr = new BufferedReader(fileis);
//											String fileString = "";
//											String line = "";
//											Log.i("日志读取","开始");
//											while((line = filebr.readLine()) != null) {
//												fileString = fileString + line + "<br>";
//											}
//											Log.i("日志读取","结束");
//											filebr.close();
//											obj2.put("logContent", fileString);
//											obj2.put("clientNo", Constant.clientNo);
//											obj2.put("todo", "writeLogContent");
//											obj2.put("fileName", info.getString("fileName"));
//											MqttClientUtil.publishTopic(Constant.actionTopic, Constant.actionQos, obj2.toJSONString(),false);
//										} catch (Exception e) {
//											e.printStackTrace();
//										}
										break;
									case "setConfig":
//										Constant.updateConfigToFile(info.getJSONObject("config"), info.getJSONObject("info"));
////									重启软件
//										AppService.reStartApp();
//										break;
//									case "adUpdate":
//										if(!info.getString("orgId").equals(Constant.orgId)) {
//											Log.i("广告更新：", "非本单位广告");
//											return;
//										}
//										//本地需要被更新的文件
//										String type = info.getString("src").split("\\.")[1];
//										File oldFile;
//										if(type.equals("jpeg")||type.equals("png")||type.equals("bmp")||type.equals("gif")) {
//											oldFile = new File(Environment.getExternalStorageDirectory().toString()+"/Pictures/"+info.getString("src"));
//										}else {
//											oldFile = new File(Environment.getExternalStorageDirectory().toString()+"/Movies/"+info.getString("src"));
//										}
//
//										//缓存网络上下载的文件
//										File newFile = new File(Environment.getExternalStorageDirectory().toString()+"/tmp/"+info.getString("src"));
//
//										HttpURLConnection httpUrl = null;
//										BufferedInputStream bis = null;
//										FileOutputStream fos = null;
//										InputStream is = null;
//										try {
//											//打开URL通道
//											URL url = new URL(Constant.adUpdateUrl+"/"+info.getString("src"));
//											httpUrl = (HttpURLConnection) url.openConnection();
//
//											httpUrl.connect();
//
//											byte[] buffer = new byte[1024];
//
//											int size = 0;
//
//											is = httpUrl.getInputStream();
//											bis = new BufferedInputStream(is);
//											fos = new FileOutputStream(newFile);
//
//											Log.i("广告更新：", "正在从网络上下载新的更新文件");
//											//保存文件
//											try {
//												while ((size = bis.read(buffer)) != -1) {
//													//读取并刷新临时保存文件
//													fos.write(buffer, 0, size);
//													fos.flush();
//												}
//											} catch (Exception ex4) {
//												Log.i("广告更新错误", ex4.getMessage());
//											}
//
//											Log.i("广告更新：", "文件下载完成");
//											//把下载的临时文件替换原有文件
//											CopyFile(oldFile,newFile);
//
//										} catch (MalformedURLException ex2) {
//											Log.i("广告更新：", "MalformedURLException");
//										} catch (IOException ex) {
//											ex.printStackTrace();
//											Log.i("广告更新：", "文件读取错误");
//										} finally {
//											try {
//												fos.close();
//												bis.close();
//												is.close();
//												httpUrl.disconnect();
//												newFile.delete();
//												AppService.reStartApp();
//											} catch (Exception ex3) {
//												ex3.printStackTrace();
//											}
//										}
										break;
									case "adDelete":
//										if(!info.getString("orgId").equals(Constant.orgId)) {
//											Log.i("广告更新：", "非本单位广告");
//											return;
//										}
//										//本地需要被更新的文件
//										String type1 = info.getString("src").split("\\.")[1];
//										File oldFile1;
//										if(type1.equals("jpeg")||type1.equals("png")||type1.equals("bmp")||type1.equals("gif")) {
//											oldFile1 = new File(Environment.getExternalStorageDirectory().toString()+"/Pictures/"+info.getString("src"));
//										}else {
//											oldFile1 = new File(Environment.getExternalStorageDirectory().toString()+"/Movies/"+info.getString("src"));
//										}
//										oldFile1.delete();
//										Log.i("广告更新：", "文件删除成功");
//										AppService.reStartApp();
										break;
									case "broadcast":
//										if(!Constant.broadcast) {
//											Log.i("远程广播", "未开启远程广播设置");
//											return;
//										}
//										//本地需要被更新的文件
//										if(info.getString("content")==null){
//											File oldFile2 = new File(Environment.getExternalStorageDirectory().toString()+"/broadcast/"+info.getString("src"));
//											if(!oldFile2.getParentFile().exists()){
//												oldFile2.getParentFile().mkdirs();
//											}
//											if(oldFile2.exists()) {
//												Log.i("远程广播", "文件已经存在");
//												//oldFile2.delete();
//												//Cache.broadcastPlayer.playMedia(oldFile2.getPath());
//												MediaPlayer mediaPlayer= new MediaPlayer();
//												mediaPlayer.setDataSource(oldFile2.getAbsolutePath());
//												mediaPlayer.prepareAsync();
//												mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
//
//													@Override
//													public void onPrepared(MediaPlayer mediaPlayer) {
//														Handler handler = MainActivity.getVideoVolHandler();
//														handler.sendMessage(handler.obtainMessage(100, "pause"));
//														mediaPlayer.start();
//													}
//												});
//												mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
//
//													@Override
//													public void onCompletion(MediaPlayer mediaPlayer) {
//														Handler handler = MainActivity.getVideoVolHandler();
//														handler.sendMessage(handler.obtainMessage(100, "play"));
//														mediaPlayer.release();
//													}
//												});
//												break;
//											}
//
//											//缓存网络上下载的文件
//											File newFile2 = new File(Environment.getExternalStorageDirectory().toString()+"/tmp/"+info.getString("src"));
//
//											HttpURLConnection httpUrl1 = null;
//											BufferedInputStream bis1 = null;
//											FileOutputStream fos1 = null;
//											InputStream is1 = null;
//											try {
//												//打开URL通道
//												URL url = new URL(Constant.broadcastUrl+"/"+info.getString("src"));
//												httpUrl1 = (HttpURLConnection) url.openConnection();
//
//												httpUrl1.connect();
//
//												byte[] buffer = new byte[1024];
//
//												int size = 0;
//
//												is1 = httpUrl1.getInputStream();
//												bis1 = new BufferedInputStream(is1);
//												fos1 = new FileOutputStream(newFile2);
//
//												Log.i("远程广播", "正在从网络上下载文件");
//												//保存文件
//												try {
//													while ((size = bis1.read(buffer)) != -1) {
//														//读取并刷新临时保存文件
//														fos1.write(buffer, 0, size);
//														fos1.flush();
//													}
//												} catch (Exception ex4) {
//													Log.i("远程广播错误", ex4.getMessage());
//												}
//
//												Log.i("远程广播", "文件下载完成");
//												//把下载的临时文件替换原有文件
//												CopyFile(oldFile2,newFile2);
//
//											} catch (MalformedURLException ex2) {
//											} catch (IOException ex) {
//												Log.i("远程广播", "文件读取错误");
//											} finally {
//												try {
//													fos1.close();
//													bis1.close();
//													is1.close();
//													httpUrl1.disconnect();
//													newFile2.delete();
//												} catch (Exception ex3) {
//													ex3.printStackTrace();
//												}
//												//Cache.broadcastPlayer.playMedia(oldFile2.getPath());
//												MediaPlayer mediaPlayer= new MediaPlayer();
//												mediaPlayer.setDataSource(oldFile2.getAbsolutePath());
//												mediaPlayer.prepareAsync();
//												mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
//
//													@Override
//													public void onPrepared(MediaPlayer mediaPlayer) {
//														Handler handler = MainActivity.getVideoVolHandler();
//														handler.sendMessage(handler.obtainMessage(100, "pause"));
//														mediaPlayer.start();
//													}
//												});
//												mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
//
//													@Override
//													public void onCompletion(MediaPlayer mediaPlayer) {
//														Handler handler = MainActivity.getVideoVolHandler();
//														handler.sendMessage(handler.obtainMessage(100, "play"));
//														mediaPlayer.release();
//													}
//												});
//
//											}
//										}else{
//											if(!"".equals(info.getString("content"))){
//												TTSUtil.speek(info.getString("content"));
//											}
//										}
										break;
									case "delBroadcast":
//										for (File file : new File(Environment.getExternalStorageDirectory().toString()+"/broadcast/").listFiles()) {
//											if(!info.getJSONArray("srcs").contains(file.getName())) {
//												file.delete();
//											}
//										}
										break;
									case "fetchAllLog":
//										Log.i("FTP","上传log文件夹中的所有日志");
//										LogUtil.updateAllLog();
										break;
									case "fetchAllVideo":
//										Log.i("FTP","上传DCIM/Camera/important文件夹中的视频");
//										try{
//											File[] videoFiles = new File(Environment.getExternalStorageDirectory()+"/DCIM/Camera/important").listFiles();
//											File[] files = new File[videoFiles.length];
//											for (int i = 0 ; i<videoFiles.length ; i++){
//												File file = new File(videoFiles[i].getParent()+"/"+Constant.clientNo+"-"+videoFiles[i].getName());
//												FileUtil.copyFile(videoFiles[i], file);
//												files[i] = file;
//											}
//											UploadUtil.uploadFiles(files,Constant.uploadVideoUrl);
//											for (File file :files) {
//												file.delete();
//											}
//										}catch (Exception e){
//											e.printStackTrace();
//										}
										break;
									case "osUpdate":
//										try{
//											DownLoadUtil.downLoadFromUrl(Constant.updateUrl+"/update.zip", "update.zip", Environment.getExternalStorageDirectory()+"/tmp");
//											File file = new File(Environment.getExternalStorageDirectory() + "/tmp/update.zip");
//											if(file.exists()){
//												Log.i("操作系统更新","开始");
//												smdt. smdtInstallPackage(Constant.context,  file);
//											}else{
//												Log.i("操作系统更新","失败，没有发现更新文件，请确保为/tmp/update.zip");
//											}
//										}catch (IOException e){
//											Log.i("操作系统更新","下载更新包失败，请确保网络上文件存在");
//										}
										break;
									case "resetAll":
//										try{
//											Log.i("系统重置","重置wifi");
//											smdt.smdtSetControl(4, 0);
//											Thread.sleep(1000);
//											smdt.smdtSetControl(4, 1);
//
//											Thread.sleep(1000);
//
//											Log.i("系统重置","重置显示器");
//											smdt.smdtSetControl(8, 0);
//											Thread.sleep(1000);
//											smdt.smdtSetControl(8, 1);
//
//											Thread.sleep(1000);
//
//											Log.i("系统重置","重置3G");
//											smdt.smdtSetControl(10, 0);
//											Thread.sleep(1000);
//											smdt.smdtSetControl(10, 1);
//
//											Thread.sleep(1000);
//
//											Log.i("系统重置","重置局域网");
//											smdt.smdtSetControl(12, 0);
//											Thread.sleep(1000);
//											smdt.smdtSetControl(12, 1);
//
//											Thread.sleep(1000);
//
//											Log.i("系统重置","重置SD卡");
//											smdt.smdtSetControl(14, 0);
//											Thread.sleep(1000);
//											smdt.smdtSetControl(14, 1);
//										}catch (Exception e){
//											Log.i("系统重置","失败");
//										}
										break;
									case "updatePeoples":
										JSONObject returnInfo = new JSONObject();
										JSONArray array = info.getJSONArray("peoples");
										JSONArray ids = new JSONArray();
										for (i = 0 ; i<array.size();i++){
											JSONObject pepole = array.getJSONObject(i);
											Cache.writeTofile(pepole.getString("id")+","+pepole.getString("name"), new FaceFeature(pepole.getBytes("faceFeature")));
											Cache.faceFeatureList.add(new Face(pepole.getString("id"),new FaceFeature(pepole.getBytes("faceFeature"))));
											ids.add(pepole.getString("id"));
										}
										returnInfo.put("todo","updatePeoplesRetuen");
										returnInfo.put("ids",ids);
										MqttClientUtil.publishTopic(Constant.returnTopic,2 ,returnInfo.toJSONString(), false);
										break;
									case "deletePeoples":
										JSONObject returnInfo2 = new JSONObject();
										JSONArray array2 = info.getJSONArray("peoples");
										JSONArray ids2 = new JSONArray();
										for (i = 0 ; i<array2.size();i++){
											JSONObject pepole = array2.getJSONObject(i);
											new File(pepole.getString("id")+","+pepole.getString("name")).delete();
											Cache.initLocalFaceFeatureFromFile();
											ids2.add(pepole.getString("id"));
										}
										returnInfo2.put("todo","deletePeoplesRetuen");
										returnInfo2.put("ids",ids2);
										MqttClientUtil.publishTopic(Constant.returnTopic,2 ,returnInfo2.toJSONString(), false);
										break;
									default:
										break;
								}
							}
						}else {

						}
					}

					@Override
					public void deliveryComplete(IMqttDeliveryToken token) {
						// TODO Auto-generated method stub
						if(token.isComplete()) {
//							StatusUI.setStatus("在线");
//							Rf433.netStatus = "0";
						}
					}

					@Override
					public void connectionLost(Throwable cause) {
						// TODO Auto-generated method stub
//						StatusUI.setStatus("离线");
//						Rf433.netStatus = "1";
						Log.i("MQTT", "已离线");
						while (true){
							try {//如果没有发生异常说明连接成功，如果发生异常，则死循环
								Thread.sleep(10000);
								Log.i("MQTT", "客户端连接中断"+sampleClient.isConnected());
								if(!sampleClient.isConnected()) {
									sampleClient.connect(connOpts);
								}else {
									MqttClientUtil.publishTopic(Constant.onlineTopic, Constant.onlineQos, Constant.onlineMsg,false);
									MqttClientUtil.subscribeTopic(Constant.actionTopic+"/"+Constant.typeId, Constant.actionQos);

									Log.i("MQTT", "重连成功");
									break;
								}
							}catch (Exception e){
								Log.i("MQTT", "断线重连中");
								continue;
							}
						}
					}
				});
				sampleClient.connect(connOpts);
				Log.i("MQTT", "已连接");
				//StatusUI.setStatus("在线");
//				Rf433.netStatus = "0";
			} catch (MqttException me) {
				Log.i("MQTT", "reason "+me.getReasonCode());
				Log.i("MQTT", "msg "+me.getMessage());
				Log.i("MQTT", "loc "+me.getLocalizedMessage());
				Log.i("MQTT", "cause "+me.getCause());
				Log.i("MQTT", "excep "+me);
				Log.i("MQTT", "网络无法连接");

				try {
					Thread.sleep(5000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				if(i<=5) {
					Log.i("MQTT", "尝试重连第"+(i)+"次");
					i++;
					try {
						sampleClient = null;
						MqttClientUtil.getInstance();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				//StatusUI.setStatus("离线");
//				Rf433.netStatus = "1";
			}
		}
		return sampleClient;
	}

	public static void publishTopic(String topic, int qos, String content, boolean retained) {
		MqttClient sampleClient = MqttClientUtil.getInstance();
		Log.i("MQTT", "正在发布消息"+content);
		MqttMessage message = new MqttMessage(content.getBytes());
		message.setQos(qos);
		message.setRetained(retained);
		try {
			sampleClient.publish(topic, message);
		} catch (MqttPersistenceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//StatusUI.setStatus("离线");
//			Rf433.netStatus = "1";
		} catch (MqttException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//StatusUI.setStatus("离线");
//			Rf433.netStatus = "1";
		}
		Log.i("MQTT", "消息发布成功");
	}

	public static void subscribeTopic(String topic, int qos) {
		MqttClient sampleClient = MqttClientUtil.getInstance();
		Log.i("MQTT", "订阅主题"+topic);
		try {
			sampleClient.subscribe(topic,qos);
		} catch (MqttPersistenceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//StatusUI.setStatus("离线");
//			Rf433.netStatus = "1";
		} catch (MqttException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//StatusUI.setStatus("离线");
//			Rf433.netStatus = "1";
		}
	}

	//复制文件
	private static void CopyFile(File oldFile, File newFile) {
		FileInputStream in = null;
		FileOutputStream out = null;

		try {
			if(oldFile.exists()){
				oldFile.delete();
			}
			in = new FileInputStream(newFile);
			out = new FileOutputStream(oldFile);

			byte[] buffer = new byte[1024 * 5];
			int size;
			while ((size = in.read(buffer)) != -1) {
				out.write(buffer, 0, size);
				out.flush();
			}

		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				out.close();
				in.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
}
